package com.joint.web.action.finance;

import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.TaskRecordService;
import com.joint.base.service.UsersService;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.finance.AuditEdit;
import com.joint.core.entity.finance.AuditNotice;
import com.joint.core.service.AuditEditService;
import com.joint.core.service.AuditLastService;
import com.joint.core.service.AuditNoticeService;
import com.joint.web.action.BaseFlowAction;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/15.
 */
@ParentPackage("finance")
public class AjaxAuditeditAction extends BaseFlowAction {
    @Resource
    private AuditEditService auditEditService;
    @Resource
    private AuditNoticeService auditNoticeService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private UsersService usersService;
    @Resource
    private TaskRecordService taskRecordService;

    private String auditId;
    private AuditEdit auditEdit;
    private AuditNotice auditNotice;
    private Users loginUser;
    private String step;
    private int numStatus;
    private String fileId;
    private String fileIds;
    private String remarks;

    public String execute(){
        return "auditedit";
    }

    public String input(){
        if(StringUtils.isNotEmpty(auditId)){
            auditNotice=auditNoticeService.get(auditId);
            auditEdit=auditNotice.getAuditEdit();
            if(StringUtils.isNotEmpty(keyId)){
                fileId="";
                if(auditEdit.getFile()!=null&&auditEdit.getFile().size()>0){
                    for(FileManage file:auditEdit.getFile()){
                        fileId+=file.getId()+",";
                    }
                }
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            auditEdit=auditEditService.get(keyId);
            fileId="";
            if(auditEdit.getFile()!=null&&auditEdit.getFile().size()>0){
                for(FileManage file:auditEdit.getFile()){
                    fileId+=file.getId()+",";
                }
            }
        }
        return "read";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            auditEdit=auditEditService.get(keyId);
        }else{
            auditEdit=new AuditEdit();
            auditEdit.setCreater(usersService.getLoginInfo());
        }
        auditEdit.setRemarks(remarks);
        auditEdit.setAuditNotice(auditNoticeService.get(auditId));
        auditEdit.setCompany(usersService.getLoginInfo().getCompany());
        List<FileManage> fileList= Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String file:fileIds.split(",")){
                fileList.add(fileManageService.get(file.trim()));
            }
        }
        auditEdit.setFile(fileList);
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                auditEditService.update(auditEdit);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                auditEditService.save(auditEdit, "auditedit", various);
            }
            AuditNotice auditNotice=auditNoticeService.get(auditId);
            auditNotice.setAuditEdit(auditEdit);
            auditNoticeService.update(auditNotice);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);

        ArrayList<String> list =Lists.newArrayList();
        List<Department> deptList=departmentService.getDepartments("产业中心");
        for(Department dept:deptList){
            Set<Power> powers = dept.getPowerSet();
            for(Power power:powers){
                if(power.getPost().getName().equals("书记")||power.getPost().getName().equals("主任")){
                    List<Users> usersList=dutyService.getPersons(dept,power.getPost());
                    for(Users user:usersList){
                        list.add(user.getId().trim());
                    }
                }
            }
        }
        var2.put("approvers",list);

        List<String> deptlist=Lists.newArrayList();
        AuditNotice auditNotice=auditNoticeService.get(auditId);
        Department dept=auditNotice.getDepartment().getParent()==null?auditNotice.getDepartment():auditNotice.getDepartment().getParent();
        for(Power power:dept.getPowerSet()){
            if(power.getPost().getName().equals("总经理")){
                List<Users> usersList=dutyService.getPersons(dept,power.getPost());
                for(Users user:usersList){
                    deptlist.add(user.getId().trim());
                }
            }
        }
        var2.put("dept",deptlist);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                auditEditService.approve(auditEdit, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = auditEditService.commit(auditEdit, "auditedit", var1, var2, curDutyId);
            }
            auditNotice.setAuditEdit(auditEdit);
            auditNotice.setStep("4");
            auditNoticeService.update(auditNotice);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve1(){
        auditEdit = auditEditService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(org.apache.commons.lang.StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
                auditEditService.approve(auditEdit, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                AuditEdit auditEdit = auditEditService.get(keyId);
                auditEdit.setProcessState(FlowEnum.ProcessState.Finished);
                auditEditService.update(auditEdit);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(auditEdit.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve2(){
        auditEdit = auditEditService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
                auditEditService.approve(auditEdit, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                AuditEdit auditEdit = auditEditService.get(keyId);
                auditEdit.setProcessState(FlowEnum.ProcessState.Finished);
                auditEditService.update(auditEdit);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(auditEdit.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 3);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3(){
        auditEdit = auditEditService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(org.apache.commons.lang.StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (org.apache.commons.lang.StringUtils.isNotEmpty(keyId)) {
                auditEditService.approve(auditEdit, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                AuditEdit auditEdit = auditEditService.get(keyId);
                auditEdit.setProcessState(FlowEnum.ProcessState.Finished);
                auditEditService.update(auditEdit);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(auditEdit.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 4);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            auditEdit = auditEditService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("auditedit");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            auditEditService.reject(auditEdit, key, numStatus, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            auditEdit = auditEditService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("auditedit");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            auditEditService.deny(auditEdit, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    public String getAuditId() {
        return auditId;
    }

    public void setAuditId(String auditId) {
        this.auditId = auditId;
    }

    public AuditEdit getAuditEdit() {
        return auditEdit;
    }

    public void setAuditEdit(AuditEdit auditEdit) {
        this.auditEdit = auditEdit;
    }

    public AuditNotice getAuditNotice() {
        return auditNotice;
    }

    public void setAuditNotice(AuditNotice auditNotice) {
        this.auditNotice = auditNotice;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getStep() {
        return step;
    }

    public void setStep(String step) {
        this.step = step;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }
}
